package com.tangsm.spring.mvc.mybatis.util;

import io.protostuff.LinkedBuffer;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import io.protostuff.ProtostuffIOUtil;

public class ProtoStuffSerializeUtil {

    /**
     * 序列化
     * @param obj 实体
     * @param <T> 实体对象
     * @return 二进制数据
     */
    public static <T> byte[] serialize(T obj) {
        if (obj == null) {
            throw new RuntimeException("Failed to serializer");
        } else {
            Class<T> clz = (Class<T>) obj.getClass();
            Schema<T> schema = RuntimeSchema.getSchema(clz);
            LinkedBuffer buffer = LinkedBuffer.allocate(1048576);

            byte[] protoStuff;
            try {
                protoStuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Failed to serializer");
            } finally {
                buffer.clear();
            }

            return protoStuff;
        }
    }

    /**
     * 反序列化
     *
     * @param paramArrayOfByte 序列号后的二进制数组
     * @param targetClass 实体Class
     * @param <T> 实体对象
     * @return 反序列化后的实体对象
     */
    public static <T> T deserialize(byte[] paramArrayOfByte, Class<T> targetClass) {
        if (paramArrayOfByte != null && paramArrayOfByte.length != 0) {
            Schema<T> schema = RuntimeSchema.getSchema(targetClass);
            T t = schema.newMessage();
            ProtostuffIOUtil.mergeFrom(paramArrayOfByte, t, schema);
            return t;
        } else {
            throw new RuntimeException("Failed to deserialize");
        }
    }
}
